package com.bjsxt.shop.head.springmvc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AUsersCar;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.orders.pojo.AOrders;
import com.bjsxt.shop.orders.pojo.AOrdersGoods;
import com.bjsxt.shop.orders.service.IOrdersService;
import com.bjsxt.shop.users.pojo.AUsers;
import com.bjsxt.shop.users.pojo.AUsersAddress;
import com.bjsxt.shop.users.service.IUsersShopService;

/**
 * 需要登陆才能访问
 * @author WangshSxt
 *
 */
@Controller
@RequestMapping("/head/orders/")
public class OrdersHeadController
{
	@Resource
	private IUsersShopService usersShopService;
	@Resource
	private IGoodsService goodsService;
	@Resource
	private IOrdersService ordersService;
	
	/**
	 * 订单打开页面
	 * 
	 * 要查询当前用户所有的已经启用的收货地址
		要查询在购物车中选择的购物车的id:(除了有商品,还有数量)
	 * 
	 * @return
	 */
	
	/**
	 *打开订单提交页面需要注意的事项 
	 *1：因为页面需要展示购物清单和收货地址，所以将会查询两个list
	 *2：查询的购物清单要根据购物车中已经选择，已经选择的ucid去查询商品
	 *3：收货地址，要查询状态正在启用的收货地址，如果用户删除了某个地址，需要把改地址的状态设置为0
	 */
	@RequestMapping("/ordersInsert")
	public String ordersInsert(String[] ucid , HttpSession session,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--ordersInsert--");
		AUsers users = (AUsers) session.getAttribute("users");
		
		/*
		 * 要查询当前用户所有的已经启用的收货地址
		 * */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/*查询用户已经启用的地址，需要通过状态为启用，同时还要根据用户的id进行查询		 */
		condMap.put("usersId", users.getId());
		condMap.put("status", "1");
		Map<String, Object> resultMap = this.usersShopService.findCondListUsersAddressService(null, condMap);
		List<AUsersAddress> usersAddressList = (List<AUsersAddress>) resultMap.get("list");
		model.addAttribute("usersAddressList", usersAddressList);
		
		/*
		 * 要查询在购物车中选择的购物车的id:(除了有商品,还有数量)
		 * */
		List<AUsersCar> usersCarList = new ArrayList<AUsersCar>();
		if(ucid != null)
		{
			for (int i = 0; i < ucid.length; i++)
			{
				String ucidTemp = ucid[i];
				/* UsersCarId:购物车
				 * 根据购物车的id查询购物车
				 *  */
				condMap.clear();
				condMap.put("id", ucidTemp);
				AUsersCar usersCar = this.goodsService.findOneUsersCarService(condMap);
				usersCarList.add(usersCar);
			}
			/*model.addAttribute("usersCarList", usersCarList);*/
		}
		/* 存储Session,之所以存储在session中，是因为在订单提交的时候还需要用到usersCarList
		 * 注意model是一次请求之间的操作，过了一次请求之后，它的值将会被取消*/
		session.setAttribute("usersCarList", usersCarList);
		return "/head/orders/ordersInsert";
	}
	
	/**
	 * 订单提交页面
	 * 
	 * ~接收参数
	 * ~赋值
	 * ~调用Service方法
	 * 
	 * @return
	 */
	/*之所以在参数列引入AOrders，是为了给orders赋予usersId的值	 */
	@RequestMapping("/ordersInsertSubmit")
	public String ordersInsertSubmit(HttpServletRequest request,AOrders orders)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--ordersInsertSubmit--");
		/* 不在jsp页面上写的属性要手工赋值 */
		
		HttpSession session = request.getSession() ;
		AUsers users = (AUsers) session.getAttribute("users");
		/* 调用用户id */
		orders.setUsersId(users.getId());
		
		/* 订单明细:怎么取
		 * 订单明细表更新，需要先查询到购物车里面的信息，然后把该信息赋值给订单明细表即可 
		 * 从Session中取,目的:安全,任何修改了订单添加页面的html,木有用
		 * 		（这里的session的作用主要是为了减少用户修改页面造成的影响，在提交订单页面要把购物车的列表存储在session中）
		 * */
		List<AOrdersGoods> ordersGoodList = new ArrayList<AOrdersGoods>();
		double totalPrice = 0 ; 
		List<AUsersCar> usersCarList = (List<AUsersCar>) session.getAttribute("usersCarList");
		for (Iterator iterator = usersCarList.iterator(); iterator.hasNext();)
		{
			/*得到购物车的信息			 */
			AUsersCar usersCar = (AUsersCar) iterator.next();
			/*得到商品的信息			 */
			AGoods goods = usersCar.getGoods();
			
			/*更新订单明细表
			 *  需要订单明细 */
			AOrdersGoods ordersGoods = new AOrdersGoods() ; 
			ordersGoods.setGoodsId(usersCar.getGoodsId());
			ordersGoods.setName(goods.getName());
			ordersGoods.setPrice(goods.getPrice());
			ordersGoods.setWeight(goods.getWeight());
			ordersGoods.setNum(usersCar.getNum());
			ordersGoods.setStatus(Byte.valueOf("1"));
			ordersGoods.setCreateTime(new Date());
			ordersGoods.setUpdateTime(new Date());
			
			/* 总价格
			 * 数量*价格 */
			ordersGoods.setTotalPrice(ordersGoods.getPrice() * ordersGoods.getNum());
			ordersGoodList.add(ordersGoods);
			totalPrice += ordersGoods.getTotalPrice() ; 
		}
		
		/* 订单的总价格 */
		orders.setTotalPrice(totalPrice);
		orders.setOrdersGoodList(ordersGoodList);
		
		orders.setCreateTime(new Date());
		orders.setUpdateTime(new Date());
		orders.setPubTime(new Date());
		/*保存一个订单，更新以上的数据		 */
		JSONObject resDbJSON = this.ordersService.saveOneOrdersService(orders);
		ConstatFinalUtil.SYS_LOGGER.info("----返回结果:{}",resDbJSON);
		
		/* 一定客户端跳转 
		 * 万恶的Dubbo,取id从返回值中取
		 * */
		String id = "" ; 
		if("0".equalsIgnoreCase(resDbJSON.get("code") + ""))
		{
			JSONObject dataJSON = (JSONObject) resDbJSON.get("data");
			id = dataJSON.get("id") + "";
		}
		/*利用请求跳转，以防用户一直注水
		 * 请求转发的时候可以在后面跟一个name=id,这样可以将参数传递到另一个controller方法中		 */
		return "redirect:/head/orders/ordersInfo.htm?oid=" + id;
	}
	
	/**
	 * 订单详情页面
	 * @return
	 */
	@RequestMapping("/ordersInfo")
	public String ordersInfo(String oid,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--ordersInfo--");
		/* 按照订单Id查询信息 */
		Map<String, Object> condMap = new HashMap();
		condMap.put("id", oid);
		AOrders orders = this.ordersService.findOneOrdersService(condMap);
		model.addAttribute("orders", orders);
		return "/head/orders/ordersInfo";
	}
}
